<script lang="ts" setup>
import { ref } from 'vue'
import { Divider } from 'ant-design-vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { importExcelSchema } from '@/views/wages/salarySlip/salarySlip.data'
import { useMessage } from '@/hooks/web/useMessage'
import { getImportTemplate } from '@/api/wages/salaryslip'
import { useI18n } from '@/hooks/web/useI18n'
import {useUserStore} from "@/store/modules/user";

defineOptions({ name: 'ImportModal' })
const emit = defineEmits(['success', 'register', 'cancel'])
const { createConfirm, createMessage } = useMessage()
const isUpdate = ref(true)
const { t } = useI18n()
const userStore = useUserStore()

const [registerForm, { getFieldsValue, resetFields, resetSchema, validate }] = useForm({
  labelWidth: 190,
  baseColProps: { span: 24 },
  schemas: importExcelSchema,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
})

/** 下载模板按钮操作 */
async function handleImportTemplate() {
  const deptId = getFieldsValue().deptId
  if (userStore.getUserInfo.roles.some(item => item === 'city_admin' || item === 'super_admin' || item === 'wages_admin')) {
    if (!deptId) {
      createMessage.info(`请先选择部门`)
      return
    }
  }
  createConfirm({
    title: t('common.importTemplateTitle'),
    iconType: 'warning',
    content: t('common.importTemplateMessage'),
    async onOk() {
      console.log('getFieldsValue()=======', getFieldsValue().deptId)
      const deptId = getFieldsValue().deptId
      await getImportTemplate(deptId || 0)
      createMessage.success(t('common.importTemplateSuccessText'))
    },
  })
}

async function cancel() {
  closeModal()
  emit('cancel')
}
</script>

<template>
  <BasicModal
    v-bind="$attrs" :min-height="100" :footer="null" :width="800" title="导入"
    @register="registerModal"
    @cancel="cancel"
  >
    <Divider />
    <BasicForm @register="registerForm" />
    <Divider />
    <div class="flex justify-between">
      <a-button type="primary" @click="cancel">
        关闭弹窗
      </a-button>
      <h3 class="mb-3 flex justify-end text-base">
        仅允许导入xls,xlsx格式文件。<a
          class="login-form-forgot" href="javaScript:void(0)"
          @click="handleImportTemplate"
        >下载模板</a>
      </h3>
    </div>
  </BasicModal>
</template>
